import styles from './index.less';
import React, { memo, PureComponent } from 'react';
import { CompnentEnums } from '@/Enums';
import ResizeDiv from '@/components/ResizeDiv';
import { connect } from 'react-redux';
import { splitStyle } from '@/utils';
const singleTags = ['br', 'hr', 'Img', 'Input', 'param', 'meta', 'Link']

/**
 * @description 节点数据发生变化
 */
let onChangeData: (data: API.Node) => void;
class Node extends PureComponent<API.Node> {
  constructor(props: API.Node) {
    super(props);
  }

  handleResize(style: { width: any, height: any }, key: string) {
    onChangeData && onChangeData({
      id: key,
      style
    });
  }


  render() {
    const { tree } = this.props;
    const type = Object.prototype.toString.call(tree);
  
    if (!tree) return <></>;

    if (type === '[object Array]') {
      return (
        <>
          {tree.map((node: API.Node) => {
            const Comp = CompnentEnums[node.tag!];

            const [outerStyle, innerStyle] = splitStyle(node.style);
       
            if (singleTags.includes(node.tag!)) {
              return (
                <ResizeDiv key={node.id} id={node.id} style={outerStyle} dragSizeChange={this.handleResize}>
                  <Comp style={innerStyle} className={styles.node} {...node.props} />
                </ResizeDiv>
              )
            }
            return (
              <ResizeDiv key={node.id} style={outerStyle} id={node.id} dragSizeChange={this.handleResize}>
                <Comp style={innerStyle} className={styles.node} {...node.props}>
                  <Node id={node.id} tree={node.children} />
                </Comp>
              </ResizeDiv>
            );
          })}
        </>
      );
    } else if (type === '[object String]') {
      return tree
    } else if (type === '[object Object]') {
      const Comp = CompnentEnums[tree.tag!];
      const [outerStyle, innerStyle] = splitStyle(tree.style);
      if (singleTags.includes(tree.tag!)) return (
        <ResizeDiv key={tree.id} style={outerStyle} id={tree.id} dragSizeChange={this.handleResize}>
          <Comp className={styles.node} style={innerStyle} {...tree.props} />
        </ResizeDiv>
      )
      return (<ResizeDiv key={tree.id} id={tree.id} style={outerStyle} dragSizeChange={this.handleResize}>
        <Comp className={styles.node} style={innerStyle} {...tree.props}>
          <Node id={tree.id} tree={tree.children} key={tree.id} />
        </Comp>
      </ResizeDiv>);
    }
  }
}
function TreeComponent(props: API.ITreeComponentProps) {
  onChangeData = function (data: any) {
    props.dispatch({
      type: 'project/saveNodeChange',
      payload: {
        ...data
      }
    });
  }
  return (<>{
    props.tree.map((node) => <Node id={node.id} tree={node} key={node.id} />)
  }</>)
}

export default connect(
)(memo(TreeComponent));